package network;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.border.EmptyBorder;

public class EchoServer extends JFrame implements Runnable {

	private JPanel contentPane;
	private JPanel panel;
	private JButton btnNewButton;
	private JButton btnNewButton_1;
	private JTextField textField;
	private JScrollPane scrollPane;
	private JTextPane result;

	ServerSocket server = null; // 두개(30,31번줄)가 가장중요!!!!!!
	Socket socket = null;
	boolean threadFlag = true; // true이면 진행

	StringBuilder data = new StringBuilder(); // 가장빠르다

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					EchoServer frame = new EchoServer();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public EchoServer() {
		setTitle("EchoServer");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		contentPane.add(getPanel(), BorderLayout.NORTH);
		contentPane.add(getScrollPane(), BorderLayout.CENTER);

		try {
			InetAddress ia = InetAddress.getLocalHost();
			setTitle(ia.getHostAddress());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setLayout(new BorderLayout(0, 0));
			panel.add(getBtnNewButton(), BorderLayout.WEST);
			panel.add(getBtnNewButton_1(), BorderLayout.EAST);
			panel.add(getTextField(), BorderLayout.CENTER);
		}
		return panel;
	}

	private JButton getBtnNewButton() {
		if (btnNewButton == null) {
			btnNewButton = new JButton("server start");
			btnNewButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try {

						threadFlag = true;
						server = new ServerSocket(4444);
						Thread t = new Thread(EchoServer.this); // this만 쓰면
																// 88라인(ActionListener)이
																// 된다.
						t.start();
						btnNewButton.setEnabled(false); // 두번이상 못누르게
						btnNewButton_1.setEnabled(true);
						data.append("<font size ='5'color='red'>서버가 시작됨</font><br/>");
						result.setText(data.toString());

					} catch (Exception ex) {

					}
				}
			});
		}
		return btnNewButton;
	}

	private JButton getBtnNewButton_1() {
		if (btnNewButton_1 == null) {
			btnNewButton_1 = new JButton("server stop");
			btnNewButton_1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {

					threadFlag = false;
					btnNewButton.setEnabled(true);
					btnNewButton_1.setEnabled(false);
					data.append("<font size ='5'color='blue'>서버가 중지됨</font><br/>");
					result.setText(data.toString());

					try {
						if (socket != null)
							socket.close();
						if (server != null)
							server.close();
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			});
		}
		return btnNewButton_1;
	}

	private JTextField getTextField() {
		if (textField == null) {
			textField = new JTextField();
			textField.setColumns(10);
		}
		return textField;
	}

	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getResult());
		}
		return scrollPane;
	}

	private JTextPane getResult() {
		if (result == null) {
			result = new JTextPane();
			result.setContentType("text/html");
		}
		return result;
	}

	@Override
	public void run() { // 서버가 접속되었는지 안되었는지 확인하고 빙빙빙

		while (threadFlag) {
			try {
				socket = server.accept();
				InetAddress ia = socket.getInetAddress();
				data.append("<b>[" + ia.getHostAddress()
						+ "] 클라이언트가 접속 되었습니다.</b><br/>");
				result.setText(data.toString());
				
				InputStream is = socket.getInputStream();
				InputStreamReader isr = new InputStreamReader(is);
				BufferedReader br = new BufferedReader(isr);
				
				String str = br.readLine();
				data.append(str);
				
				result.setText(data.toString());
					

			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}
}
